//
//  CMDBLoginViewController.swift
//  CMDB
//
//  Created by 曹桂祥 on 17/4/6.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit

class CMDBLoginViewController: CustomNormalContentViewController {
    
    private var loginParam: CMDBLoginParam = CMDBLoginParam()
    
    let leftMargin = (CMDB_Screen_Width - 630 * CMDB_Rate) * 0.5
    
    lazy var phoneLabel : CustomTF = {
        
        let phoneLabel = CustomTF()
        
        phoneLabel.iconImageName         = "手机"
        
        phoneLabel.leftLabel.text        = "手机号码:"
        
        phoneLabel.leftLabel.textColor   = UIColor.Hex6(labelBlackColor, alpha:labelFirBlackAlpha)
        
        phoneLabel.textColor             = UIColor.Hex6(labelBlackColor, alpha: labelSecBlacklAlpha)
        
        phoneLabel.leftFont              = CMDB_16_FONT
        
        phoneLabel.tid                   = "phone"
        
        phoneLabel.keyBoardType          = .NumberPad
        
        phoneLabel.returnKeyType         = .Default
        
        phoneLabel.maxLength             = 11
        
        phoneLabel.attributedPlaceHolder = NSAttributedString(string: "请输入手机号", attributes: [NSFontAttributeName: CMDB_16_FONT,NSForegroundColorAttributeName: UIColor.Hex6(labelBlackColor, alpha: labelSecBlacklAlpha)])
        
        return phoneLabel
        
    }()
    
    // 已有账号
    private lazy var forgetLink : M80AttributedLabel? = {
        
        var forgetLink = M80AttributedLabel()
        
        forgetLink.textAlignment = .Center
        
        forgetLink.textColor = UIColor.Hex(0x007eff)
        
        forgetLink.linkColor = UIColor.Hex(0x007eff)
        
        forgetLink.underLineForLink = true
        
        forgetLink.font = CMDB_16_FONT
        
        return forgetLink
    }()
    
    
    
    
    lazy var secretLabel : CustomTF = {
        
        let secretLabel = CustomTF()
        
        secretLabel.iconImageName         = "密码"
        
        secretLabel.leftLabel.text        = "登录密码:"
        
        secretLabel.leftLabel.textColor   = UIColor.Hex6(labelBlackColor, alpha: labelFirBlackAlpha)
        
        secretLabel.textColor             = UIColor.Hex6(labelBlackColor, alpha: labelSecBlacklAlpha)
        
        secretLabel.tid                   = "psw"
        
        secretLabel.leftFont              = CMDB_16_FONT
        
        secretLabel.keyBoardType          = .Default
        
        secretLabel.returnKeyType         = .Done
        
        secretLabel.secureTextEntry       = true
        
        secretLabel.attributedPlaceHolder = NSAttributedString(string: "请输入密码", attributes: [NSFontAttributeName:CMDB_16_FONT,NSForegroundColorAttributeName : UIColor.Hex6(labelBlackColor, alpha: labelSecBlacklAlpha)])
        
        return secretLabel
        
    }()
    
    private var register: TSAttributedLabel =  {
        
        let label = TSAttributedLabel()
        
        label.textColor = UIColor.lightGrayColor()
        
        label.textAlignment = .Center
        
        label.font = CMDB_15_FONT
        
        return label
    }()
    
    private var loginButton = UIButton(type: .Custom)
    
    override func setup() {
        super.setup()
        
        buildSubViews()
        
    }
}

// MARK: buoldViews
extension CMDBLoginViewController{
    
    private func buildSubViews(){
        
        buildLogoView()
        
        buildInputView()
        
        buildBottomView()
        
        buildRegView()
    }
    
    private func buildLogoView(){
        
        let logoImage = UIImageView(frame: CGRect(x: 0, y: 50, width: 160 * CMDB_Rate, height: 160 * CMDB_Rate))
        
        logoImage.centerX = (contentView?.middleX)!
        
        logoImage.image = UIImage(named: "logo")
        
        contentView?.addSubview(logoImage)
        
    }
    
    private func buildInputView(){
        
        buildPhoneView()
        
        buildSecView()
    }
    
    private func buildBottomView(){
        
        loginButton.setTitle("登录", forState: .Normal)
        loginButton.setTitle("登录", forState: .Highlighted)
        
        loginButton.setTitleColor(UIColor.Hex6(0xffffff, alpha: 0.87), forState: .Highlighted)
        
        loginButton.setTitleColor(UIColor.Hex6(0xffffff), forState: .Normal)
        
        loginButton.backgroundColor = UIColor.Hex6(0xff6d00, alpha: 0.87)
        
        loginButton.titleLabel!.font = CMDB_17_FONT
        
        let leftMargin = (width - 630 * CMDB_Rate) * 0.5
        
        loginButton.frame = CGRect(x: leftMargin, y: 680 * CMDB_Rate, width: 630 * CMDB_Rate, height: 88 * CMDB_Rate)
        
        loginButton.addTarget(self, action: #selector(loginTriggrred), forControlEvents: .TouchUpInside)
        
        loginButton.layer.cornerRadius = 5
        
        contentView?.addSubview(loginButton)
        
        forgetLink?.delegate = self
        
        forgetLink?.text = "忘记密码?"
        
        forgetLink?.sizeToFit()
        
        let forgetLinkRange: NSRange = ((forgetLink?.text!)! as NSString).rangeOfString("忘记密码?")
        
        forgetLink?.addCustomLink("忘记密码?",forRange: forgetLinkRange)
        
        forgetLink?.frame = CGRect(x: width - (width - 630 * CMDB_Rate) * 0.5 - forgetLink!.width, y: 600 * CMDB_Rate, width: forgetLink!.width, height: forgetLink!.height)
        
        contentView?.addSubview(forgetLink!)
    }
    
    private func buildRegView() {
        
        contentView?.addSubview(register)
        
        register.underLindeForLink = false
        
        register.linkColor = UIColor.lightGrayColor()
        
        let text: NSString = "还没有账号？受邀注册 >>"
        
        register.setText(text as String)
        
        let range = text.rangeOfString(text as String)
        
        register.addCustomLink(range, forRange: range)
        
        register.addTargetForLinkResponse(self, action: #selector(registerResponse))
        
        //        register.frame = CGRectMake(0, CGRectGetMaxY(loginButton.frame) + 150 * CMDB_Rate, CMDB_Screen_Width, 100 * CMDB_Rate)
        register.snp_makeConstraints { [weak self] (make) in
            
            make.left.equalTo(0)
            
            make.right.equalTo(0)
            
            make.top.equalTo(self!.loginButton.snp_bottom).offset(150 * CMDB_Rate)
        }
        
    }
    
    
}
extension CMDBLoginViewController {
    
    @objc private func registerResponse(link: TSAttributedLinkBean) {
        
        let reg = CMDBRegisterViewController()
        
        reg.title = "填写资料"
        
        navigationController?.pushViewController(reg, animated: true)
    }
}


extension CMDBLoginViewController: M80AttributedLabelDelegate {
    func m80AttributedLabel(label: M80AttributedLabel ,clickedOnLink linkData: AnyObject) {
        if label == forgetLink! {
            
            onItemClickType("forgetLink", data: nil, indexPath: nil)
            
        }
    }
}


extension CMDBLoginViewController{
    
    func loginTriggrred() {
        
        CMDBShowInfoManager.getInstance.showWithStatus("登录中...")
        
        loginParam.phone = phoneLabel.text!
        
        loginParam.password = secretLabel.text!
        
        do {
            
            try CMDBLoginManager.getInstance.login(loginParam, handler: { [weak self] (account) in
                
                CMDBShowInfoManager.getInstance.showSuccessStatus("登录成功")
                
//                if account.isAssociate  {
//                    
//                    UIApplication.sharedApplication().keyWindow?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
//                    
//                } else {
//                    
//                    let associate = CMDBAssociateViewController()
//                    
//                    associate.title = "关联作品"
//                    
//                    self!.navigationController?.pushViewController(associate, animated: true)
//                }
                
                UIApplication.sharedApplication().keyWindow?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
                
                }, error: { (rescode) in
                    
                }, faliure: {
                    
                    CMDBShowInfoManager.getInstance.popActivity()
                    
            })
            
        } catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.PhoneInvalid) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("无效手机号!")
            
            
        } catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.PasswordInvalid) {
            
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("请输入6-12位密码!")
            
        } catch CMDBUserControllerExceptionType.ExceptionCode(code: .PhoneIsEmpty){
            
             CMDBShowInfoManager.getInstance.showInfoWithStatus("手机号不能为空")
            
        } catch CMDBUserControllerExceptionType.ExceptionCode(code: .PasswordIsEmpty){
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("密码不能为空")
            
        } catch {
            
            printLog(error)
            
        }
    }
    
}

extension CMDBLoginViewController
{
    override func onItemClickType(itemClickType: String?, data: AnyObject?, indexPath: NSIndexPath?) {
        print("done")
        
    }
}

extension CMDBLoginViewController{
    
    internal func buildPhoneView(){
        
        phoneLabel.mDelegate = self
        
        phoneLabel.frame = CGRect(x: leftMargin, y: 320 * CMDB_Rate, width:630 * CMDB_Rate , height: 120 * CMDB_Rate)
        
        contentView?.addSubview(phoneLabel)
    }
    
    internal func buildSecView(){
        
        secretLabel.mDelegate = self
        
        secretLabel.frame = CGRect(x: leftMargin, y: 440 * CMDB_Rate, width:630 * CMDB_Rate , height: 120 * CMDB_Rate)
        
        contentView?.addSubview(secretLabel)
    }
}

// MARK: override superClass's method
extension CMDBLoginViewController{
    
    override func buildTitleView() {
        super.buildTitleView()
        
        let titleLabel             = UILabel()
        
        let titleStr               = "登录"
        
        let titleRichStr           = NSMutableAttributedString(string: titleStr)
        
        titleRichStr.addAttributes([NSForegroundColorAttributeName:UIColor.Hex6(0xFFFFFF, alpha: 0.87)], range: NSMakeRange(0, titleRichStr.length))
        
        titleRichStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(CGFloat(22))], range: NSMakeRange(0, titleRichStr.length))
        
        titleLabel.attributedText  = titleRichStr
        
        titleLabel.sizeToFit()
        
        titleView?.addSubview(titleLabel)
        
        let middleY                = (titleView?.middleY)! + 5
        
        titleLabel.center          = CGPoint(x: (titleView?.middleX)!, y: middleY)
        
    }
    
    override func buildContentView() {
        super.buildContentView()
        
        contentView?.backgroundColor = UIColor.whiteColor()
    }
}
